<template>
  <div>
    <!-- 面包屑导航 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/welcome' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>用户管理</el-breadcrumb-item>
      <el-breadcrumb-item>用户列表</el-breadcrumb-item>
    </el-breadcrumb>
    <!-- 卡片区域 -->
    <el-card>
      <!-- 输入查询框 -->
      <el-row :gutter="20">
        <el-col :span="7">
          <!-- 调用获取数据方法 -->
          <el-input placeholder="请输入内容" v-model="userQuery.query" clearable @clear="getUserList()">
            <el-button slot="append" icon="el-icon-search" @click="getUserList()"></el-button>
          </el-input>
        </el-col>
        <el-col :span="7">
          <el-button type="primary" @click="addDialogVisible=true">添加用户</el-button>
        </el-col>
      </el-row>
      <!-- 用户列表区域 -->
      <el-table :data="userList" stripe border>
        <el-table-column type="index"></el-table-column>
        <el-table-column label="姓名" prop="username"></el-table-column>
        <el-table-column label="邮箱" prop="email"></el-table-column>
        <el-table-column label="电话" prop="mobile"></el-table-column>
        <el-table-column label="角色" prop="role_name"></el-table-column>
        <el-table-column label="状态">
          <!-- 作用域插槽，获取该行数据 ,会覆盖prop-->
          <template slot-scope="scope">
            <el-switch v-model="scope.row.mg_state" @change="UserInfoChanged(scope.row)"></el-switch>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="200px">
          <template slot-scope="scope">
            <el-button
              type="primary"
              icon="el-icon-edit"
              size="mini"
              @click="changeUserdialogVisible(scope.row.id)"
            ></el-button>
            <el-button
              type="danger"
              icon="el-icon-delete"
              size="mini"
              @click="deletetUserdialogVisible(scope.row.id)"
            ></el-button>
            <el-tooltip effect="dark" content="分配角色" placement="top" :enterable="false">
              <el-button
                type="warning"
                icon="el-icon-setting"
                size="mini"
                @click="rolesAssign(scope.row)"
              ></el-button>
            </el-tooltip>
          </template>
        </el-table-column>
      </el-table>
      <!-- 分页区域 -->
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="userQuery.pagenum"
        :page-sizes="[1, 2, 5,10]"
        :page-size="userQuery. pagesize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
      ></el-pagination>
    </el-card>

    <!-- 添加用户框 -->
    <!-- 监听close事件，该close事件方法是特有的 -->
    <el-dialog title="添加用户" :visible.sync="addDialogVisible" width="50%" @close="addFromClosed">
      <el-form
        :model="addForm"
        status-icon
        :rules="addFormRules"
        ref="addFormRef"
        label-width="100px"
      >
        <el-form-item label="用户名" prop="username">
          <el-input type="text" v-model="addForm.username" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="密码" prop="password">
          <el-input type="password" v-model="addForm.password" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input type="text" v-model="addForm.email" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="手机" prop="mobile">
          <el-input type="text" v-model="addForm.mobile" autocomplete="off"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="addDialogVisible=false">取 消</el-button>
        <el-button type="primary" @click="addUser">确 定</el-button>
      </span>
    </el-dialog>

    <!-- 修改用户信息框 -->
    <el-dialog
      title="修改用户信息"
      :visible.sync="editUserdialogVisible"
      width="50%"
      @close="editFromClosed"
    >
      <el-form
        :model="editFrom"
        label-width="100px"
        :rules="changeFormRules"
        status-icon
        ref="editFromRef"
      >
        <el-form-item label="用户名">
          <el-input type="text" v-model="editFrom.username" autocomplete="off" disabled></el-input>
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input type="text" v-model="editFrom.email" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="手机" prop="mobile">
          <el-input type="text" v-model="editFrom.mobile" autocomplete="off"></el-input>
        </el-form-item>
      </el-form>

      <span slot="footer" class="dialog-footer">
        <el-button @click="editUserdialogVisible=false">取 消</el-button>
        <el-button type="primary" @click="changeUser">确 定</el-button>
      </span>
    </el-dialog>

    <!-- 分配角色对话框 -->
    <el-dialog title="分配角色" :visible.sync="roleDialogvisible" width="50%" @close="RolesCloseBtn">
      <div>
        <p>当前的用户:{{this.userInfo.username}}</p>
        <p>当前的角色:{{this.userInfo.role_name}}</p>
        <p>
          分配新角色:
          <el-select v-model="selectRoleId" placeholder="请选择">
            <!-- label指定看到的列表项。value指定选中的列表元素 -->
            <el-option
              v-for="item in rolesList"
              :key="item.id"
              :label="item.roleName"
              :value="item.id"
            ></el-option>
          </el-select>
        </p>
      </div>
      <span slot="footer">
        <el-button @click="roleDialogvisible = false">取 消</el-button>
        <el-button type="primary" @click="savaRoleInfo">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
export default {
  data() {
    // 自定义表单验证规则
    // 验证邮箱的规则
    var checkEmail = (rule, value, callback) => {
      // 验证邮箱的正则表达式
      const regEmail = /^([a-zA-Z0-9_-])+@([a-zA-Z0-9_-])+(\.[a-zA-Z0-9_-])+/
      if (regEmail.test(value)) {
        return callback()
      } else {
        callback(new Error('请输入合法的邮箱'))
      }
    }
    // 验证手机的规则
    var checkMoblie = (rule, value, callback) => {
      // 验证手机号码的正则表达式
      const regMoblie = /^(0|86|17951)?(13[0-9]|15[0123456789]|17[678]|18[0-9]|14[57])[0-9]{8}$/
      if (regMoblie.test(value)) {
        return callback()
      } else {
        callback(new Error('请输入合法的手机号码'))
      }
    }
    return {
      userQuery: {
        query: '',
        // 当前的页数
        pagenum: 1,
        // 当前每页显示多少条数据
        pagesize: 2
      },
      // 存放获取到的数据
      userList: [],
      // 存放数据总数
      total: 0,
      // 添加用户信息
      addDialogVisible: false,
      // 修改用户信息
      editUserdialogVisible: false,
      // 用户分配权限
      roleDialogvisible: false,
      // 获取到的用户权限信息
      userInfo: {},

      // 获取角色列表
      rolesList: [],

      // 选中的id值
      selectRoleId: '',

      // 添加用户的表单数据
      addForm: {
        username: '',
        password: '',
        email: '',
        mobile: ''
      },
      // 修改用户信息
      editFrom: {},
      // 添加表单验证规则对象
      addFormRules: {
        // 用户名验证
        username: [
          { required: true, message: '请输入用户名称', trigger: 'blur' },
          {
            min: 3,
            max: 10,
            message: '长度在 3 到 10 个字符',
            trigger: 'blur'
          }
        ],
        // 密码验证
        password: [
          { required: true, message: '请输入密码', trigger: 'blur' },
          {
            min: 6,
            max: 15,
            message: '长度在 6 到 15 个字符',
            trigger: 'blur'
          }
        ],
        // 邮箱验证
        email: [
          { required: true, message: '请输入邮箱', trigger: 'blur' },
          { validator: checkEmail, trigger: 'blur' }
        ],
        // 手机号码验证
        mobile: [
          { required: true, message: '请输入手机号码', trigger: 'blur' },
          { validator: checkMoblie, trigger: 'blur' }
        ]
      },
      changeFormRules: {
        // 邮箱验证
        email: [
          { required: true, message: '请输入邮箱', trigger: 'blur' },
          { validator: checkEmail, trigger: 'blur' }
        ],
        // 手机号码验证
        mobile: [
          { required: true, message: '请输入手机号码', trigger: 'blur' },
          { validator: checkMoblie, trigger: 'blur' }
        ]
      }
    }
  },
  created() {
    this.getUserList()
  },
  methods: {
    // 用户管理信息数据请求方法
    async getUserList() {
      const { data: res } = await this.$http.get('users', {
        params: this.userQuery
      })
      // console.log(res)
      if (res.meta.status !== 200) {
        return this.$message.error('获取用户列表失败')
      }
      this.userList = res.data.users
      this.total = res.data.total
    },
    // 每页数据条数
    handleSizeChange(newSize) {
      // console.log(newSize)
      this.userQuery.pagesize = newSize
      this.getUserList()
    },
    // 页码总数
    handleCurrentChange(newPage) {
      // console.log(newPage)
      this.userQuery.pagenum = newPage
      this.getUserList()
    },
    // 修改后台状态
    async UserInfoChanged(userinfo) {
      // console.log(userinfo)

      const { data: res } = await this.$http.put(
        `users/${userinfo.id}/state/${userinfo.mg_state}`
      )
      if (res.meta.status !== 200) {
        // 如果更新失败，把页面上已经修改了的状态重置回去
        userinfo.mg_state = !userinfo.mg_state
        return this.$message.error('更新用户状态失败')
      } else {
        this.$message.success('更新用户状态成功')
      }
    },
    // 监听添加用户框的开关情况，并清除填写内容
    addFromClosed() {
      this.$refs.addFormRef.resetFields()
    },

    // 添加用户
    addUser() {
      // 使用validate触发表单验证
      this.$refs.addFormRef.validate(async valid => {
        if (!valid) return
        // 发起添加用户请求
        const { data: res } = await this.$http.post('users', this.addForm)
        if (res.meta.status !== 201) {
          return this.$message.error('添加用户失败')
        } else {
          // 隐藏添加用户框
          this.addDialogVisible = false
          // 弹出提示框
          this.$message.success('添加用户成功')
          // 重新获取用户信息数据，从而刷新页面
          this.getUserList()
        }
      })
    },

    // 通过id查询用户信息
    async changeUserdialogVisible(id) {
      // 注意这里请求路径的写法!
      const { data: res } = await this.$http.get('users/' + id)
      if (res.meta.status !== 200) {
        return this.$message.error('查询用户信息失败')
      }
      this.editFrom = res.data
      // 拿到后台数据并显示对话框
      this.editUserdialogVisible = true
      // console.log(id)
    },
    // 对未修改成功的数据进行复原
    editFromClosed() {
      this.$refs.editFromRef.resetFields()
    },
    //提交并修改用户信息
    changeUser() {
      this.$refs.editFromRef.validate(async valid => {
        // 发起修改用户信息的请求
        const { data: res } = await this.$http.put(
          'users/' + this.editFrom.id,
          {
            email: this.editFrom.email,
            mobile: this.editFrom.mobile
          }
        )
        if (res.meta.status !== 200)
          return this.$message.error('修改用户信息失败')
        this.$message.success('修改用户信息成功')

        // 更新用户信息
        this.getUserList()

        // 隐藏对话框
        this.editUserdialogVisible = false
      })
    },
    // 根据id删除对应用户
    async deletetUserdialogVisible(id) {
      //  弹出确认弹窗
      const confirmResult = await this.$confirm(
        '此操作将永久删除该用户, 是否继续?',
        '提示',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }
      ).catch(err => err)
      // 如果点击确认，输出字符串confirm
      // 如果点击取消，输出字符串cancel
      // console.log(confirmResult)
      if (confirmResult !== 'confirm') {
        return this.$message('已取消删除')
      } else {
        const { data: res } = await this.$http.delete('users/' + id)
        if (res.meta.status !== 200)
          return this.$message.error('删除用户信息失败')
        this.$message.success('删除用户信息成功')
        this.getUserList()
      }
    },
    // 为用户分配权限
    async rolesAssign(userInfo) {
      this.userInfo = userInfo
      const { data: res } = await this.$http.get('roles')
      if (res.meta.status !== 200) {
        return this.$message.error('获取权限数据失败')
      }
      this.rolesList = res.data
      this.roleDialogvisible = true
    },
    // 保存用户角色设置
    async savaRoleInfo() {
      if (!this.selectRoleId) {
        return this.$message.error('请选择要分配的角色！')
      }

      const {
        data: res
      } = await this.$http.put(`users/${this.userInfo.id}/role`, {
        rid: this.selectRoleId
      })
      if (res.meta.status !== 200) {
        return this.$message.error('更新角色失败！')
      }
      this.$message.success('更新角色成功！')

      this.getUserList()
      this.roleDialogvisible = false
    },
    // 用户关闭分配角色对话框，自动清除数据,对于选择框的处理方法
    RolesCloseBtn() {
      this.selectRoleId = ''
      this.userInfo = {}
    }
  },
  components: {}
}
</script>

<style lang="less" scoped>
</style>
